package xulong.com.weiyulinked.service;

import jakarta.servlet.http.HttpSession;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import xulong.com.weiyulinked.mapper.FriendMapper;
import xulong.com.weiyulinked.mapper.UserInfoMapper;
import xulong.com.weiyulinked.model.Friend;
import xulong.com.weiyulinked.model.Result;
import xulong.com.weiyulinked.model.UserInfo;

import java.util.ArrayList;
import java.util.List;

@Service
@Slf4j
public class UserService {
    @Autowired
    private UserInfoMapper userInfoMapper;
    @Autowired
    private FriendMapper friendMapper;

    public Result<UserInfo> userLogin(UserInfo userInfo, HttpSession session) {
        UserInfo info = userInfoMapper.selectByUsername(userInfo.getUsername());
        if (info == null) {
            return Result.fail("未查询到用户");
        }
        // 校验密码是否正确
        if (!userInfo.getPassword().equals(info.getPassword())) {
            return Result.fail("密码错误");
        }
        // 登录成功，将用户信息放入session
        session.setAttribute("user", info);
        return Result.success(info);
    }

    public Result<UserInfo> userRegister(UserInfo userInfo) {
        try {
            userInfoMapper.insert(userInfo);
            return Result.success(userInfo);
        } catch (Exception e) {
            return Result.fail("用户名已存在");
        }
    }

    public List<UserInfo> getFriendList(Integer userId) {

        List<Friend> friendList = friendMapper.getFriendList(userId);
        log.info("好友列表：{}", friendList);
        if (friendList==null) {
            return new ArrayList<>();
        }
        List<UserInfo> userInfoList = new ArrayList<>();
        for (Friend friend : friendList) {
            UserInfo userInfo = userInfoMapper.selectById(friend.getFriendId());
            userInfoList.add(userInfo);
        }
        log.info("好友列表用户信息：{}", userInfoList);
        return userInfoList;
    }
}
